package cn.lhf.cd.controller;

import cn.lhf.cd.Main;
import cn.lhf.cd.annotation.FXController;
import cn.lhf.cd.mapper.UserMapper;
import cn.lhf.cd.utils.StringUtils;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import org.apache.ibatis.session.SqlSession;

import java.net.URL;
import java.util.ResourceBundle;

@FXController(path = "/ui/change_password.fxml")
public class ChangePasswordController extends ChildrenController {
    public PasswordField oldPasswordField;
    public PasswordField newPasswordField;
    public PasswordField rePasswordField;
    public Label tipLabel;

    @Override
    public String getTitle() {
        return "修改密码窗口";
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    @Override
    public void onBtnLeft4() throws Exception {
        getMainController().goHome();
    }

    @Override
    public void onBtnRight4() throws Exception {
        String oldPassword = oldPasswordField.getText();    //原码
        if (StringUtils.isEmpty(oldPassword)) {
            sendTip(tipLabel, "请输入原密码！");
            return;
        }
        String newPassword = newPasswordField.getText();    //新密码
        if (StringUtils.isEmpty(newPassword)) {
            sendTip(tipLabel, "请输入新密码！");
            return;
        }
        String rePassword = rePasswordField.getText();      //重复密码
        if (StringUtils.isEmpty(rePassword)) {
            sendTip(tipLabel, "请输入确认密码！");
            return;
        }
        if (!newPassword.equals(rePassword)) {
            sendTip(tipLabel, "两次输入密码不一致！");
            return;
        }
        SqlSession sqlSession = Main.openSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        if (!oldPassword.equals(userMapper.getPassword(getMainController().getSelfId()))) {
            sendTip(tipLabel, "密码错误！");
        } else {
            clearTips();
            userMapper.changePassword(getMainController().getSelfId(), newPassword);
            getMainController().setFrameView(SuccessController.class, "修改密码成功，%d秒后将返回主界面");
        }
        sqlSession.commit();
        sqlSession.close();
    }

}
